<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\AchievementService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AchievementController extends Controller
{
    private $achievementService;

    public function __construct(AchievementService $achievementService)
    {
        $this->achievementService = $achievementService;
    }

    /**
     * 获取所有可获得的成就
     */
    public function index(Request $request)
    {
        $cacheKey = 'all_achievements';
        
        $achievements = Cache::remember($cacheKey, 3600, function () {
            return $this->achievementService->getAllAchievements();
        });

        return $this->success($achievements, '获取成就列表成功');
    }

    /**
     * 获取用户成就
     */
    public function userAchievements(User $user, Request $request)
    {
        // 检查是否为当前用户或有权限查看
        if ($user->id !== $request->user()->id) {
            return $this->error('无权查看其他用户的成就', 403);
        }

        $userAchievements = $user->achievements()
                                ->orderBy('unlocked_at', 'desc')
                                ->get();

        $allAchievements = $this->achievementService->getAllAchievements();
        $unlockedKeys = $userAchievements->pluck('achievement_key')->toArray();

        $formattedAchievements = collect($allAchievements)->map(function ($achievement) use ($unlockedKeys, $userAchievements) {
            $isUnlocked = in_array($achievement['key'], $unlockedKeys);
            $userAchievement = $userAchievements->where('achievement_key', $achievement['key'])->first();

            return [
                'key' => $achievement['key'],
                'name' => $achievement['name'],
                'description' => $achievement['description'],
                'category' => $achievement['category'],
                'difficulty' => $achievement['difficulty'],
                'rewards' => $achievement['rewards'],
                'is_unlocked' => $isUnlocked,
                'unlocked_at' => $isUnlocked ? $userAchievement->unlocked_at : null,
                'progress' => $isUnlocked ? 100 : $this->achievementService->getAchievementProgress($user, $achievement['key']),
            ];
        });

        $stats = [
            'total_achievements' => count($allAchievements),
            'unlocked_count' => $userAchievements->count(),
            'completion_rate' => count($allAchievements) > 0 ? round(($userAchievements->count() / count($allAchievements)) * 100, 1) : 0,
            'recent_unlocked' => $userAchievements->take(3)->map(function ($achievement) {
                return [
                    'key' => $achievement->achievement_key,
                    'name' => $achievement->achievement_name,
                    'unlocked_at' => $achievement->unlocked_at,
                ];
            }),
        ];

        return $this->success([
            'achievements' => $formattedAchievements,
            'stats' => $stats,
        ], '获取用户成就成功');
    }

    /**
     * 检查用户成就
     */
    public function checkAchievements(User $user, Request $request)
    {
        // 检查是否为当前用户
        if ($user->id !== $request->user()->id) {
            return $this->error('无权为其他用户检查成就', 403);
        }

        try {
            $newAchievements = $this->achievementService->checkAllAchievements($user);

            if (empty($newAchievements)) {
                return $this->success([], '暂无新成就解锁');
            }

            return $this->success([
                'new_achievements' => $newAchievements,
                'count' => count($newAchievements),
            ], '恭喜！解锁了新成就！');

        } catch (\Exception $e) {
            return $this->error('成就检查失败', 500);
        }
    }
}